﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

//Class made by microchip
//Source: http://www.dreamincode.net/forums/topic/14788-c%23-fast-acces-to-bitmap-pixels/

namespace THO7_Team8
{
    public unsafe class UnsafeBitmap
    {
        Bitmap bitmap;

        int width;
        BitmapData bitmapData = null;
        Byte* pBase = null;

        public UnsafeBitmap(Bitmap bmp)
        {
            bitmap = new Bitmap(bmp);
        }

        public UnsafeBitmap(int width, int height)
        {
            bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
        }

        public void Dispose()
        {
            bitmap.Dispose();
        }

        public Bitmap Bitmap
        {
            get
            {
                return bitmap;
            }
        }

        public void LockBitmap()
        {
            //GraphicsUnit unit = GraphicsUnit.Pixel;
            //RectangleF boundsF = bitmap.GetBounds(ref unit);
            Rectangle bounds = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            // Figure out the number of bytes in a row
            // This is rounded up to be a multiple of 4
            // bytes, since a scan line in an image must always be a multiple of 4 bytes
            // in length. 
            width = (int)bitmap.Width * sizeof(PixelData);
            if (width % 4 != 0)
            {
                width = 4 * (width / 4 + 1);
            }
            bitmapData = bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            pBase = (Byte*)bitmapData.Scan0.ToPointer();
        }

        public PixelData GetPixel(int x, int y)
        {
            return *(PixelData*)(pBase + y * width + x * sizeof(PixelData));
        }

        public void SetPixel(int x, int y, PixelData colour)
        {
            *((PixelData*)(pBase + y * width + x * sizeof(PixelData))) = colour;
        }

        public void UnlockBitmap()
        {
            bitmap.UnlockBits(bitmapData);
            bitmapData = null;
            pBase = null;
        }
    }

    public struct PixelData
    {
        public byte blue;
        public byte green;
        public byte red;
    }
}

